import baseUrl from '@/config/url.js'
export default class Api {
    defaultHeaders = {}
    setDefaultHeaders(headers) {
        this.defaultHeaders = headers;
    }

    addDefaultHeader(key, value) {
        this.defaultHeaders[key] = value;
    }

    removeDefaultHeader(key) {
        delete this.defaultHeaders[key];
    }

    get(url, params, header) {
        return this.request(url, "GET", params, header);
    }

    post(url, params, header) {
        return this.request(url, "POST", params, header);
    }

    request(url = '', method = 'GET', params = {}, header = {}) {
        return new Promise((resolve, reject) => {
            let reqUrl;
            if (url.startsWith('http') || url.startsWith('https')) {
                reqUrl = url;
            } else {
                reqUrl = baseUrl + url;
            }
            let token = uni.getStorageSync('token')
            let body = {
                url: reqUrl,
                data: params,
                method: method,
                timeout: 30 * 1000,
                responseType: 'text',
                header: {
                    // 默认值
                   	"Content-Type": "application/x-www-form-urlencoded",
                     "token": token,
                    ...header
                },
                success(res) {
                    resolve(res.data)
                    if (res.data.code == 401) {
                        uni.clearStorageSync()
						uni.showModal({
							title:'提示',
							content:"暂未登录，请点击去登录",
							success:res=>{
								if(res.confirm){
									uni.navigateTo({
										url:'/pages/login/login'
									})
								}
							}
						})
                    }
					if (res.data.code == 500) {
						uni.showToast({
							title:'服务器错误',
							icon:'none'
						})
					}
                },
                fail: (res) => {
					uni.hideLoading()
					uni.clearStorageSync()
					uni.showToast({
						title:'连接服务器失败',
						icon:'none'
					})
                    // console.log("请求失败：",reqUrl,res)
                    reject(res.data)
                }
            }
            try {
                uni.request(body)
            } catch (e) {
                console.log(e)
                reject(res);
            }

        });
    }
}
